package thread_try;

import java.util.concurrent.TimeUnit;

public class VolatileSingleton {
    public int key=0;
    private static volatile boolean stop = false;
    public static volatile VolatileSingleton volatileSingleton;

    // 构造函数私有，禁止外部实例化
    private VolatileSingleton() {}

    // 使用 Singleton.class 作为锁，确保线程安全
    public static VolatileSingleton getInstance() {
        if (volatileSingleton == null) {
            synchronized (VolatileSingleton.class) {
                if (volatileSingleton == null) {
                    volatileSingleton = new VolatileSingleton();
                }
            }
        }
        return volatileSingleton;
    }


    public static void main(String[] args) {
        VolatileSingleton v = VolatileSingleton.getInstance();
        System.out.println(++v.key);
        VolatileSingleton v2 = VolatileSingleton.getInstance();
        System.out.println(v.equals(v2));
        System.out.println(v2.key);

        // volatile测试
        new Thread("Thread A") {
            @Override
            public void run() {
                while (!stop) {
//                    System.out.println("Loop...");
                }
                System.out.println(Thread.currentThread() + " stopped");
            }
        }.start();

        // Thread-main
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread() + " after 1 seconds");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stop = true;
    }
}
